using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using StudentVideo.Shared.Models;

namespace StudentVideo.Filters;

public class HttpResultFilter(ILogger<HttpResultFilter> logger): IResultFilter {
   private readonly ILogger<HttpResultFilter> _logger = logger;

   public void OnResultExecuting(ResultExecutingContext context) {
      if (context.Result is not BadRequestObjectResult badRequestObjectResult)
         return;

      if (badRequestObjectResult.Value is not ValidationProblemDetails derails)
         return;

      var result = new HttpResult<object> {
         StatusCode = 400,
         Message = "参数异常",
         Data = null
      };

      string paramLog = "参数验证异常: \n";
      foreach (var error in derails.Errors) {
         var keyStr = $"{error.Key}: ";
         var indentLen = keyStr.Length;

         paramLog += keyStr;
         int index = 0;
         foreach (var info in error.Value) {
            paramLog += index == 0 ? info : info.PadLeft(info.Length + indentLen);

            index++;
         }
      }
      _logger.LogWarning("{paramLog}", paramLog);

      context.Result = new ObjectResult(result) {
         StatusCode = 200
      };
   }

   public void OnResultExecuted(ResultExecutedContext context) {
      // Console.Write(context);
   }
}
